//
//  UIImageView+LoadImagesFromInternet.m
//  groupecards
//
//  Created by Alan Chen on 12/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UIImageView+LoadImagesFromInternet.h"
#import "NSString+Utilities.h"

#define kNameOfLoadingImage @"image_loading.png"
#define kNameOfErrorImage @"image_error.png"

@implementation UIImageView (LoadImagesFromInternet)

- (void)loadImageAsynchronousWithURL:(NSString *)url placeHolderImage:(NSString *)placeholder
{
    if(nil == url || [url isEqualToString:@""])
    {
        self.image = [UIImage imageNamed:placeholder];
        return;
    }
    NSFileManager *manager =[NSFileManager defaultManager];
    NSArray *array = [url componentsSeparatedByString:@"/"];
    NSString *imageName = [array lastObject];
    NSString *imagePath = [[NSString getImagesDirectory] stringByAppendingPathComponent:imageName];
    if([manager fileExistsAtPath:imagePath])
    {
        self.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else
    {
        //if the image view is subview of tablecell, retain the cell while loading image
        if([self.superview.superview isKindOfClass:[UITableViewCell class]])
            [self.superview.superview retain];
        
        self.image = [UIImage imageNamed:kNameOfLoadingImage];
        Downloader *imageDownloader = [[Downloader alloc] init];
        imageDownloader.purpose = imagePath;
        imageDownloader.delegate = self;
        [imageDownloader startDownloadWithURL:url];
        [imageDownloader release];
    }
}
#pragma -
#pragma DownloaderDelegate methods
- (void)downloader:(Downloader*)downloader completeWithNSData:(NSData*)data
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if(![manager fileExistsAtPath:[NSString getImagesDirectory]])
        [manager createDirectoryAtPath:[NSString getImagesDirectory] withIntermediateDirectories:NO attributes:nil error:nil];
    if([data writeToFile:downloader.purpose atomically:NO])
    {
        self.image = [UIImage imageWithData:data];
    }
    if([self.superview.superview isKindOfClass:[UITableViewCell class]])
        [self.superview.superview release];
}
- (void)downloader:(Downloader*)downloader didFinishWithError:(NSString*)message
{
    self.image = [UIImage imageNamed:kNameOfErrorImage];
    if([self.superview.superview isKindOfClass:[UITableViewCell class]])
        [self.superview.superview release];
}
@end
